from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from houses.models import House
from orders.models import Order
from users.models import User


class HouseSerializer(ModelSerializer):
    """房源信息序列化器"""

    # user_id = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())
    house_id = serializers.IntegerField(label='房源ID', read_only=True, source='id')
    img_url = serializers.CharField(label='图片URL', read_only=True, source='index_image_url')
    area_name = serializers.StringRelatedField(label='城区名称', read_only=True, source='area')
    # todo:c_time 格式和要求有些不一样
    c_time = serializers.DateTimeField(label='房源创建时间', read_only=True, source='create_time')
    # index_image_url = serializers.CharField(label='房源首页图片URL', write_only=True)
    acreage = serializers.IntegerField(label='房屋面积', write_only=True)
    unit = serializers.CharField(label='房屋单元配置', write_only=True)
    capacity = serializers.IntegerField(label='容纳人数', write_only=True)
    beds = serializers.CharField(label='床铺配置', write_only=True)
    deposit = serializers.IntegerField(label='押金', write_only=True)
    min_days = serializers.IntegerField(label='最少入住天数', write_only=True)
    max_days = serializers.IntegerField(label='最多入住天数', write_only=True)

    class Meta:
        model = House
        exclude = ('user', 'area', 'create_time', 'update_time', 'id', 'index_image_url')
        # 补充验证
        extra_kwargs = {
            "price": {'min_value': 0},
            "room_count": {'min_value': 0, 'max_value': 100},
            "acreage": {'min_value': 0},
            "capacity": {'min_value': 1, 'max_value': 100},
            "deposit": {'min_value': 0},
            "min_days": {'min_value': 1},
            "max_days": {'min_value': 0}
        }


class HouseSimpleSerializer(ModelSerializer):
    """简单房源信息序列化器"""
    house_id = serializers.IntegerField(label='房源ID', read_only=True, source='id')
    img_url = serializers.CharField(label='图片URL', read_only=True, source='index_image_url')

    class Meta:
        model = House
        fields = ('house_id', 'title', 'img_url')


class OrderCommentSerializer(ModelSerializer):
    """订单评论信息序列化器"""
    user = serializers.StringRelatedField(label='订单用户名')

    # todo create_time 名字改成ctime
    # 用于关系嵌套序列化器
    class Meta:
        model = Order
        fields = ('comment', 'user', 'create_time')


class HouseDetailSerializer(ModelSerializer):
    """房源详情信息序列化器"""
    # 关联对象嵌套序列化
    hid = serializers.IntegerField(label='房源ID', source='id')
    comments = OrderCommentSerializer(label='订单评论信息', many=True, source='order_set')
    img_urls = serializers.StringRelatedField(label='房源图片URL', many=True, source='houseimage_set')
    user_id = serializers.PrimaryKeyRelatedField(label='用户ID', read_only=True)

    class Meta:
        model = House
        exclude = ('update_time', 'create_time', 'order_count',
                   'index_image_url', 'area', 'user', 'id')
